/**
 * 成品明细库存表
 */
const menuId = 403;
const PRINT_TEMPLATE_NAME = 'cpRepository.cpt';
//库存表
$(function () {
    getreportStartDate();

    initKendoUiGrid();
    btn_refresh();
});

/**
 * 将数组去重
 * @param arr
 * @param attribute
 * @returns {[]}
 */
function unique(arr, attribute) {
    let new_arr = [];
    let json_arr = [];
    for (let i = 0; i < arr.length; i++) {
        if (new_arr.indexOf(arr[i][attribute]) == -1) {
            new_arr.push(arr[i][attribute]);
            json_arr.push(arr[i]);
        }
    }
    return json_arr;
}

function initKendoUiGrid(data) {

    var id = new kendo.data.DataSource({data: []});
    var fid = new kendo.data.DataSource({data: []});
    var supplier = new kendo.data.DataSource({data: []});
    var batch = new kendo.data.DataSource({data: []});
    var ylgg = new kendo.data.DataSource({data: []});
    var converter = new kendo.data.DataSource({data: []});
    var billtype = new kendo.data.DataSource({data: []});
    var bill_date = new kendo.data.DataSource({data: []});
    var memo = new kendo.data.DataSource({data: []});

    var dataSource = new kendo.data.DataSource({
        data: data,

        schema: {
            model: {
                fields: {
                    boxnumber: {type: "number"},
                    qty: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "boxnumber", aggregate: "sum"},
            {field: "qty", aggregate: "sum"},
        ],

        change: function (e) {
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;
            id.data(unique(data, 'id'));
            supplier.data(unique(data, 'supplier'));
            batch.data(unique(data, 'batch'));
            ylgg.data(unique(data, 'ylgg'));
            converter.data(unique(data, 'converter'));
            billtype.data(unique(data, 'billtype'));
            fid.data(unique(data, 'fid'));

            //Qty.data(unique(data, 'Qty'));
            // B_GJ.data(unique(data, 'B_GJ'));
            // FHQty.data(unique(data, 'FHQty'));
            bill_date.data(unique(data, 'b_date'));
            memo.data(unique(data, 'b_memo'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('disable')
                }
            })
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });
    var grid = $("#bill").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: true,
        title: "报表",
        columnMenu: {
            sortable: true
        },
        excel: {
            fileName: "计划单序时表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        pageable: {
            pageSize: 200
        },
        dataSource: dataSource,
        columns: [
            {
                field: "", title: "序号", width: 30,
                template: "<span class='row_number'></span>", width: 40
            },
            {
                field: "id",
                hidden: true,
                title: 'id',
                width: 30,
                attributes: {style: 'white-space:nowrap;'},
                headerAttributes: {style: 'text-align:left;margin-right: 2px;'},
                footerAttributes: {style: 'color: red;text-align:center;'}
            },
            {
                field: "fid",
                hidden: true,
                title: 'fid',
                width: 30,
                attributes: {style: 'white-space:nowrap;'},
                headerAttributes: {style: 'text-align:left;margin-right: 2px;'},
                footerAttributes: {style: 'color: red;text-align:center;'}
            },

            {
                field: "billtype",
                title: '单据类型',
                width: 100,
                filterable: {multi: true, search: true, dataSource: supplier},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: "supplier",
                title: '供应商',
                width: 100,
                filterable: {multi: true, search: true, dataSource: supplier},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: "converter",
                title: '加工商',
                width: 100,
                filterable: {multi: true, search: true, dataSource: supplier},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'batch',
                title: '批次号',
                width: 100,
                filterable: {multi: true, search: true, dataSource: batch},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'ylgg',
                title: '原料规格',
                width: 100,
                filterable: {multi: true, search: true, dataSource: ylgg},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },

            {
                field: 'boxnumber',
                title: '箱数',
                width: 100,
                template: item => item['boxnumber'] ? parseFloat(item['boxnumber']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'qty',
                title: '入库重量',
                width: 100,
                template: item => item['qty'] ? parseFloat(item['qty']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: "memo",
                title: '开单备注',
                width: 150,
                filterable: {multi: true, search: true, dataSource: memo},
                attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: "bill_date",
                title: '入库日期',
                width: 100,
                filterable: {multi: true, search: true, dataSource: bill_date},
                attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },


        ],
        reorderable: true,
        height: '99%',
        dataBound: function () {
            var rows = this.items();
            $(rows).each(function () {
                var index = $(this).index() + 1;
                var rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
        },
    });
    var grid01 = $("#bill").data("kendoGrid");
    //双击事件
    grid.on('dblclick', 'tr', function () {
        //  代码
        var kGrid = $("#bill").data("kendoGrid");
        var row = kGrid.select();
        var dataItem = kGrid.dataItem(row);
        var id = dataItem['id'];
        var fid=dataItem['fid']
        // window.parent.addTab('原料入库', 'makeyldetail.html?id=' + id);

        m_PlanID=id;
        m_fid=fid;
        if (m_fid>0){
            $('#B').window('open');  // close a window
            openplanB(m_PlanID);
        }else {
            $('#A').window('open');  // close a window
            openplanA(m_PlanID);
        }
        console.log(id);
    });
    //右击事件
    grid.on('contextmenu', 'tr', function (e) {
        e.preventDefault();
        //  代码

    });
    //  单击事件
    grid.on('click', 'tr', function () {
        //  代码

    });
}

//新增
function addplan() {
    // window.parent.addTab('原料计划', 'makeyldetail.html?id=0');

    $('#A').window('open');  // close a window
    m_PlanID=null;
    openplanA(m_PlanID);
}

//打开领料页面
function addLLB() {
    var kGrid = $("#bill").data("kendoGrid");
    var row = kGrid.select();
    var dataItem = kGrid.dataItem(row);
    var id = dataItem['id'];
    var fid=dataItem['fid'];

    if(id>0){
        if (fid>0){
            $.messager.alert('提示', '请选择一行有效的入库数据再进行领料！');
            return;
        }else{
            m_PlanID=id;
            m_fid=fid;

            $('#B').window('open');  // close a window
            openplanB(m_PlanID);
        }
    }else{
        $.messager.alert('提示', '请选择一行有效的入库数据再进行领料！');
        return;
    }
}

//刷新
function btn_refresh() {
    var kGrid = $("#bill").data("kendoGrid");
    // var row = kGrid.select();
    // var dataItem = kGrid.dataItem(row);

    var data1 = $('#start').datebox('getValue');
    var data2 = $('#end').datebox('getValue');

    console.log(strLin + '/greyinto/chro/'+ data1 + "/" + data2);
    $.ajax({
        url: strLin + '/greyinto/chro/'+ data1 + "/" + data2 ,
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            let data=cdata.data;
            console.log(data);
            kGrid.dataSource.data(data);
        }

    });

}

//打印
function btn_print() {
    let kGrid = $("#bill").data("kendoGrid");
    if (kGrid == undefined) {
        $.messager.alert('提示', '网格组件异常！请刷新重试！');
        return;
    }
    let filtrer = kGrid.dataSource.filter();
    let allData = kGrid.dataSource.data();
    let query = new kendo.data.Query(allData);
    let data = query.filter(filtrer).data;
    if (data != undefined && data.length > 0) {
        let arr = [];
        for (let i = 0; i < data.length; i++) {
            let item = data[i]['planId'];
            if (item) arr.push(item);
        }
        if (arr.length <= 0) return;
        let reportlets = [];
        let printTemplate = {};
        printTemplate.ids = arr.join(',');
        printTemplate.reportlet = PRINT_TEMPLATE_NAME;
        reportlets.push(printTemplate);
        if (reportlets.length <= 0) {
            $.messager.show({title: '提示', msg: '没有明细！无法打印！'});
            return;
        }
        let config = {
            url: "ReportServer",
            isPopUp: false,
            data: {
                reportlets: reportlets
            }
        };
        FR.doURLPDFPrint(config);
    }
}

//导出
function btn_export() {
    let kGrid = $("#bill").data("kendoGrid");
    if (kGrid == undefined) {
        $.messager.alert('提示', '网格组件异常！请刷新重试！');
        return;
    }
    kGrid.saveAsExcel();
}

//重置
function btn_reset() {
    $.messager.show('提示', '该页面暂无chongzh业务！');
}

//  清除
function btn_cancel_filter() {
    let kGrid = $("#bill").data("kendoGrid");
    if (kGrid != undefined) {
        kGrid.dataSource.filter({});
    }
}

//右键菜单弹出框
function menuHandler() {

}

function getDate(param) {
    if (isNaN(param)) {
        param = 0;
    }
    var curDate = new Date();
    var newDate = new Date(curDate);
    newDate.setDate(curDate.getDate() + param);
    var year = newDate.getFullYear();
    var month = newDate.getMonth() + 1 < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1;
    var date = newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate();
    var separator = '-';
    return year + separator + month + separator + date;
}

//关闭当前标签页事件
function closeTab() {
    window.parent.closeTab();
}

//获取报表对应的起始日期
function getreportStartDate() {
    $.ajax({
        url: strLin + '/configAll/all',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            let  data=cdata.data;
            console.log(data);
            data1=data.filter(item=>item.config_name==="原料入库_pc");
            var starDate=getDay(-data1[0].value_num);
            console.log(starDate);
            $("#start").datebox("setValue", starDate);
            btn_refresh();

        }
    })
}